package cn.service;

import cn.constant.Messages;
import cn.entity.Article;
import cn.entity.Comment;
import cn.entity.User;
import cn.repository.CommentRepository;
import cn.util.AuthUtils;
import cn.web.model.VmUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author m on 2023/1/29
 * Description:
 */
@Service
public class CommentServiceImpl implements CommentService{

    private final CommentRepository commentRepository;

    @Autowired
    public CommentServiceImpl(CommentRepository commentRepository) {
        this.commentRepository = commentRepository;
    }

    @Override
    public Comment createComment(Comment comment) {
        return commentRepository.save(comment);
    }

    @Override
    public Messages deleteComment(UUID id,String token) {
        Comment comment = commentRepository.findById(id).orElse(null);
        VmUser user = AuthUtils.getUser(token);
        if (comment == null) {
            return Messages.WRONG_ID;
        }

        if(comment.getUser().getType() == User.TYPE_ORDINARY){
            if(comment.getUser().getId() != user.getId()){
                return Messages.NO_PERMISSION;
            }
        }

        List<Comment> comments = comment.getReplyComment();

        for (Comment comment1 : comments) {
            commentRepository.delete(comment1);
        }
        commentRepository.delete(comment);
        return Messages.SUCCESS;
    }

    @Override
    public Integer countByArticle(Article article) {
        List<Comment> comments = new ArrayList<>();
        commentRepository.findAllByOrderByCreateTimeDesc()
                .forEach(comment -> {
                    if(is(comment.getArticle().getId(),article.getId())){
                        comments.add(comment);
                    }
                });
        return comments.size();
    }

    @Override
    public void replyComment(Comment comment,Comment replyComment) {
        List<Comment> comments = replyComment.getReplyComment();
        comments.add(comment);
        replyComment.setReplyComment(comments);
    }

    @Override
    public Comment getById(UUID id) {
        return commentRepository.findById(id).orElse(null);
    }

    //获取评论数
    public boolean is(UUID commentId,UUID articleId){
        if(commentId==articleId){
            return true;
        }
        return false;
    }
}
